import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/',
    redirect: '/home',
    component: () => import('@/views/layout'),
    children: [
      {
        path: '/home',
        component: () => import('@/views/home')
      },
      {
        path: '/article',
        component: () => import('@/views/article')
      },
      {
        path: '/publish',
        component: () => import('@/views/publish')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航前置守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  // 有token情况
  if (getToken()) {
    // 如果要去登录页，直接跳转至首页
    // 如果要去其他页面，正常跳转
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
    // 没有token情况
  } else {
    // 如果要去登录页，正常跳转
    // 如果要去其他页面，直接跳转至登录页
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

// 导航后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
})

export default router
